package com.example.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.LinkedBlockingQueue;

@Service
@Slf4j
public class MultiThreadExchangeService {

    private CyclicBarrier barrier;
    private final LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<>();

    @PostConstruct
    public void initialize() {
        // CyclicBarrier设置为等待3个线程
        this.barrier = new CyclicBarrier(3, () -> {
            log.info("所有线程已到达屏障，开始交换数据...");
            // 模拟数据交换
            String data1 = queue.poll();
            String data2 = queue.poll();
            String data3 = queue.poll();
            log.info("交换结果: {}, {}, {}", data1, data2, data3);
        });
    }

    public void executeMultiThreadExchangeTask() {
        // 启动多个线程来演示 CyclicBarrier
        for (int i = 0; i < 3; i++) {
            new Thread(() -> {
                try {
                    String data = "来自线程 " + Thread.currentThread().getName() + " 的数据";
                    log.info("线程 {} 正在交换数据: {}", Thread.currentThread().getName(), data);
                    queue.put(data);
                    barrier.await(); // 等待其他线程到达屏障
                } catch (Exception e) {
                    log.error("线程 {} 发生异常", Thread.currentThread().getName(), e);
                }
            }).start();
        }
    }
}
